package org.halk.controller;

import org.halk.util.pdf.HtmlToPdfUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/pdf")
public class PdfExportController {

    @Resource
    private TemplateEngine templateEngine;


    @GetMapping("/export")
    public void exportPdf(HttpServletResponse response) throws IOException {

        Map<String, Object> objMap = new HashMap<>();
        objMap.put("head", "this is pdf 的头部");
        objMap.put("items", "你hi啊哦哦哦哦");
        objMap.put("baseUri", getBaseUri());

        String siteName = "北京师范大学";
        String projectId = "HOR";
        String projectName = "横断";
        String createDateStr = "2024-01-01 09:09";

        //封面数据
        Map<String, String> headMap = new HashMap<>();
        headMap.put("siteName", siteName);
        headMap.put("projectName", projectName + "正式采集数据质量分析报告");
        headMap.put("createDateStr", "该份报告的统计时间截止到 " + createDateStr);

        objMap.put("head", headMap);

        // 生成PDF文件
        String pdfPath = "E:/1.pdf";
        Context context = new Context();
        objMap.forEach(context::setVariable);
        String htmlStr = templateEngine.process("index", context);
        HtmlToPdfUtils.convertStringToPdf(htmlStr, pdfPath);
    }


    public String getBaseUri() {
        try {
            org.springframework.core.io.Resource resource = new ClassPathResource("templates/");
            return resource.getURL().toString();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }
}
